package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.demo.repository.*;
import server.demo.entity.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private TicketRepository ticketRepository;
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    @Autowired
    private TrainRepository trainRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private SeatRepository seatRepository;
    
    /**
     * 获取系统总体统计信息
     */
    public Map<String, Object> getOverallStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 订单统计
        long totalOrders = orderRepository.count();
        long pendingOrders = orderRepository.countByOrderStatus(Order.OrderStatus.PENDING);
        long paidOrders = orderRepository.countByOrderStatus(Order.OrderStatus.PAID);
        long confirmedOrders = orderRepository.countByOrderStatus(Order.OrderStatus.CONFIRMED);
        long cancelledOrders = orderRepository.countByOrderStatus(Order.OrderStatus.CANCELLED);
        long refundedOrders = orderRepository.countByOrderStatus(Order.OrderStatus.REFUNDED);
        
        stats.put("totalOrders", totalOrders);
        stats.put("pendingOrders", pendingOrders);
        stats.put("paidOrders", paidOrders + confirmedOrders); // 将已确认订单也算作已付款
        stats.put("cancelledOrders", cancelledOrders);
        stats.put("refundedOrders", refundedOrders);
        
        // 票务统计
        long totalTickets = ticketRepository.count();
        long validTickets = ticketRepository.countByTicketStatus(Ticket.TicketStatus.VALID);
        long usedTickets = ticketRepository.countByTicketStatus(Ticket.TicketStatus.USED);
        long cancelledTickets = ticketRepository.countByTicketStatus(Ticket.TicketStatus.CANCELLED);
        
        stats.put("totalTickets", totalTickets);
        stats.put("validTickets", validTickets);
        stats.put("usedTickets", usedTickets);
        stats.put("cancelledTickets", cancelledTickets);
        
        // 用户统计
        long totalUsers = userRepository.count();
        long adminUsers = userRepository.countByRole(User.UserRole.ADMIN);
        long normalUsers = userRepository.countByRole(User.UserRole.USER);
        
        stats.put("totalUsers", totalUsers);
        stats.put("adminUsers", adminUsers);
        stats.put("normalUsers", normalUsers);
        
        // 车次统计
        long totalTrains = trainRepository.count();
        long activeTrains = trainRepository.countByStatus(Train.TrainStatus.ACTIVE);
        long cancelledTrains = trainRepository.countByStatus(Train.TrainStatus.CANCELLED);
        
        stats.put("totalTrains", totalTrains);
        stats.put("activeTrains", activeTrains);
        stats.put("cancelledTrains", cancelledTrains);
        
        // 座位统计
        long totalSeats = seatRepository.count();
        long availableSeats = seatRepository.countByIsAvailable(true);
        long occupiedSeats = seatRepository.countByIsAvailable(false);
        
        stats.put("totalSeats", totalSeats);
        stats.put("availableSeats", availableSeats);
        stats.put("occupiedSeats", occupiedSeats);
        
        return stats;
    }
    
    /**
     * 获取今日统计
     */
    public Map<String, Object> getTodayStatistics() {
        Map<String, Object> stats = new HashMap<>();
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();
        
        // 今日订单
        long todayOrders = orderRepository.countByCreatedAtBetween(startOfDay, endOfDay);
        stats.put("todayOrders", todayOrders);
        
        // 今日票务销售
        long todayTickets = ticketRepository.countByCreatedAtBetween(startOfDay, endOfDay);
        stats.put("todayTickets", todayTickets);
        
        // 今日新用户
        long todayUsers = userRepository.countByCreatedAtBetween(startOfDay, endOfDay);
        stats.put("todayUsers", todayUsers);
        
        return stats;
    }
    
    /**
     * 获取收入统计
     */
    public Map<String, Object> getRevenueStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总收入（已付款和已确认订单）
        BigDecimal paidRevenue = orderRepository.sumTotalAmountByOrderStatus(Order.OrderStatus.PAID);
        if (paidRevenue == null) paidRevenue = BigDecimal.ZERO;
        
        BigDecimal confirmedRevenue = orderRepository.sumTotalAmountByOrderStatus(Order.OrderStatus.CONFIRMED);
        if (confirmedRevenue == null) confirmedRevenue = BigDecimal.ZERO;
        
        BigDecimal totalRevenue = paidRevenue.add(confirmedRevenue);
        stats.put("totalRevenue", totalRevenue);
        
        // 待收入（待付款订单）
        BigDecimal pendingRevenue = orderRepository.sumTotalAmountByOrderStatus(Order.OrderStatus.PENDING);
        if (pendingRevenue == null) pendingRevenue = BigDecimal.ZERO;
        stats.put("pendingRevenue", pendingRevenue);
        
        // 退款金额
        BigDecimal refundedAmount = orderRepository.sumTotalAmountByOrderStatus(Order.OrderStatus.REFUNDED);
        if (refundedAmount == null) refundedAmount = BigDecimal.ZERO;
        stats.put("refundedAmount", refundedAmount);
        
        return stats;
    }
    
    /**
     * 获取热门车次统计（根据订单数量）
     */
    public List<Object[]> getPopularTrains(int limit) {
        return orderRepository.findPopularTrainsByOrderCount(limit);
    }
    
    /**
     * 获取热门线路统计
     */
    public List<Object[]> getPopularRoutes(int limit) {
        return ticketRepository.findPopularRoutes(limit);
    }
    
    /**
     * 获取用户订单统计
     */
    public Map<String, Object> getUserOrderStatistics(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        long totalOrders = orderRepository.countByUserId(userId);
        long paidOrders = orderRepository.countByUserIdAndOrderStatus(userId, Order.OrderStatus.PAID);
        long pendingOrders = orderRepository.countByUserIdAndOrderStatus(userId, Order.OrderStatus.PENDING);
        long cancelledOrders = orderRepository.countByUserIdAndOrderStatus(userId, Order.OrderStatus.CANCELLED);
        
        stats.put("totalOrders", totalOrders);
        stats.put("paidOrders", paidOrders);
        stats.put("pendingOrders", pendingOrders);
        stats.put("cancelledOrders", cancelledOrders);
        
        // 用户总消费
        BigDecimal totalSpent = orderRepository.sumTotalAmountByUserIdAndOrderStatus(userId, Order.OrderStatus.PAID);
        if (totalSpent == null) totalSpent = BigDecimal.ZERO;
        stats.put("totalSpent", totalSpent);
        
        return stats;
    }
    
    /**
     * 获取车次余票统计
     */
    public Map<String, Object> getTrainSeatAvailability(Long trainId) {
        Map<String, Object> stats = new HashMap<>();
        
        long totalSeats = seatRepository.countByTrainId(trainId);
        long availableSeats = seatRepository.countByTrainIdAndIsAvailable(trainId, true);
        long occupiedSeats = totalSeats - availableSeats;
        
        stats.put("trainId", trainId);
        stats.put("totalSeats", totalSeats);
        stats.put("availableSeats", availableSeats);
        stats.put("occupiedSeats", occupiedSeats);
        stats.put("occupancyRate", totalSeats > 0 ? (double) occupiedSeats / totalSeats * 100 : 0);
        
        return stats;
    }
}